package com.shell.customer.accreditation.rx;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.sequence.SequenceHelper;
import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.po.CusOpt;
import com.shell.customer.po.CusRec;
import com.shell.feign.ContractTransferFeigh;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;

@Component
public class UpdateCusSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private CusRecService customerCService;
	@Autowired
	private ContractTransferFeigh contractTransferFeigh;

	public void onApplicationEvent(AccreditEvent event) {
		AccreditationVo accreditationVo = event.getAccreditationVo();
		CusRec cus = accreditationVo.getCustomerC();
		CusOpt cusOpt = event.getCusOpt();
		String currentState = cusOpt.getCurState();

		cus.setCusState(cusOpt.getCusState());
		if (cus.getCusState().equals("E")) {
			String cusCode = "";
			CusRec cusTmp = new CusRec();
			List<CusRec> cusTmps = null;
			do {
				cusCode = SequenceHelper.generateCode("RG", 6);
				cusTmp.setCusCode(cusCode);
				cusTmps = this.customerCService.selectByEntity(cusTmp);
			} while ((null != cusTmps) && (cusTmps.size() > 0));
			cus.setCusCode(cusCode);
		}
		if (("on".equals(SpringContextUtil.getProperty("contract.switch"))) && ("2".equals(cusOpt.getBizCode()))
				&& (StringUtil.trimEmpty(cusOpt.getNextState()))) {
			this.contractTransferFeigh.entUserSyncById(cus.getCusId());
		}
		int affectedRows = this.customerCService.updateCustomerOptimistically(cus, currentState);
		if (affectedRows != 1) {
			throw new UnCheckMsgException("������������������������");
		}
	}
}
